package com.quantumoctopus.magiceatball;

import java.util.ArrayList;
import java.util.Random;

import android.content.SharedPreferences;

import com.google.gson.JsonElement;

//this does nothing right now
public class QuizManager {

	private String URL = "http://api.yelp.com/v2/search?term=restaurant+food";
	private String ll = "";
	private String category_filter = "";
	private String sort = "";
	private String radius_filter = "";
	private String limit = "";
	private String offset = "";
	private int pricePreference = 0;
	private boolean newloc;
	private boolean pricecare;
	private String logs = "";
	private QuestionBuilder qb;
	private String[] types = { "location", "price", "category", "DONE" };
	private Question currentQuestion;
	private int currentQuestionType = 0;
	private ArrayList<Question> currentQuestionList;
	private int currentQuestionIndex = 0;
	private int priceFilter = 4;
	// private ArrayList<Result> resultList;

	public static final String DEFAULT_SORT = "1";
	public static final String DEFAULT_RADIUS_FILTER = "2000";

	public Question startQuiz(String resource) {
		qb = new QuestionBuilder();
		qb.loadQuestions(resource);
		currentQuestionList = qb
				.getArrayListOfQuestions(types[currentQuestionType]);
		currentQuestion = currentQuestionList.get(currentQuestionIndex);
		return currentQuestion;
	}

	public Question nextQuestion() {
		switch (currentQuestionType) {
		case 0:
			currentQuestion = currentQuestionList.get(currentQuestionIndex);
			break;
		case 1:
			currentQuestion = currentQuestionList.get(currentQuestionIndex);
			break;
		case 2:
			Random rand = new Random();
			currentQuestionIndex = rand.nextInt(currentQuestionList.size());
			currentQuestion = currentQuestionList.get(currentQuestionIndex);
			break;

		}
		return currentQuestion;
	}

	public void LoadPrefs(SharedPreferences sp) {
		// radius_filter=sp.getString("distance", "5"); //unsure on actual
		// number to be used for radius_filter
		// ll=sp.getString("geodata", "34.425958581828425,-119.88632478962093");
		setPrice(sp.getInt("price", 4));
		newloc = sp.getBoolean("newloc", false);
		setLogs(sp.getString("savedlogslist", ""));
		pricecare = sp.getBoolean("pricecare", true);
		radius_filter=sp.getString("distance", "2000");

	}

	public boolean answerQuestion(String answerText) {
		switch (currentQuestionType) {
		case 0:
			// if get a answer that causes you to move on, or last question in
			// set, go to next type
			if ((answerText.equals(currentQuestion.getAnswer(0)) || (currentQuestionIndex == currentQuestionList
					.size() - 1))) {
				appendURL(currentQuestion.getAnswerEffect(answerText));
				currentQuestionList = qb
						.getArrayListOfQuestions(types[++currentQuestionType]);
				currentQuestionIndex = 0;
			} else
				currentQuestionIndex++;
			break;
		case 1:
			if ((answerText.equals(currentQuestion.getAnswer(0)) || (currentQuestionIndex == currentQuestionList
					.size() - 1))) {
				priceFilter = Integer.parseInt(currentQuestion
						.getAnswerEffect(answerText));
				currentQuestionList = qb
						.getArrayListOfQuestions(types[++currentQuestionType]);
			} else
				currentQuestionIndex++;
			break;
		case 2:
			// if the answer is yes, this category is done, otherwise remove the
			// current question
			if ((answerText.equals(currentQuestion.getAnswer(0)) || (currentQuestionList
					.size() == 1))) {
				appendURL(currentQuestion.getAnswerEffect(answerText));
				currentQuestionType++;
				currentQuestionIndex = 0;
			} else
				currentQuestionList.remove(currentQuestionIndex);
			break;
		}

		// if quiz is done, return false, else return true

		if (currentQuestionType == types.length - 1)
			return false;
		else
			return true;
	}

	// Latitude and Logitude in the format "lat,long"
	public void addLocation() {

		StringBuilder sb = new StringBuilder();
		sb.append(URL);
		sb.append("&ll=");
		sb.append(ll);
		URL = sb.toString();
	}

	public void addCategory() {

		StringBuilder sb = new StringBuilder();
		sb.append(URL);
		sb.append("&category_filter=");
		sb.append(category_filter);
		URL = sb.toString();
	}

	public void addSort() {

		StringBuilder sb = new StringBuilder();
		sb.append(URL);
		sb.append("&sort=");
		sb.append(sort);
		URL = sb.toString();
	}

	public void addRadius() {

		StringBuilder sb = new StringBuilder();
		sb.append(URL);
		sb.append("&radius_filter=");
		sb.append(radius_filter);
		URL = sb.toString();
	}

	public ArrayList<Result> getResultList(String coordinates) {
		setLl(coordinates);
		setSort(DEFAULT_SORT);
		addLocation();
		addSort();

		String signedURL = YelpURLSigner.getURLString(URL);
		JsonElement jse = null;
		try {
			jse = JSONWorker.getJSONElementFromString(JSONWorker
					.getJSONString(signedURL));
		} catch (Exception e) {
			e.printStackTrace();
		}

		ArrayList<Result> resultsList = new ArrayList<Result>();

		int numResults = Integer
				.parseInt(ResultsWorker.getNumberOfResults(jse));

		if (numResults > 20)
			numResults = 20;

		for (int i = 0; i < numResults; i++) {
			Result r = ResultsWorker.buildResult(ResultsWorker
					.getJsonArrayOfBusinesses(jse).get(i));
			// r.setPrice(ResultsWorker.getPrice(r.getUrl()));
			resultsList.add(r);
		}

		return resultsList;
	}

	
	//Given a arraylist of results, returns a result filtered by price.
	public Result filterResultList(ArrayList<Result> resultList) {
		int random;
		Result r = null;

		if (pricePreference < priceFilter)
			priceFilter = pricePreference;

		while (resultList.size()>0) {
			Random rand1 = new Random();
			random = rand1.nextInt(resultList.size());
			r = resultList.get(random);
			if (pricecare == false && newloc==false) {
				return r;

			}
			if (newloc == true) {
				if (logs.contains(r.getId()) == false) {
					if (pricecare == true) {
						if (ResultsWorker.getPrice(r.getUrl()) <= priceFilter) {
							return r;
						} else
							resultList.remove(random);

					} else
						return r;
				} else
					resultList.remove(random);
			}
			if (newloc == false) {
				if (ResultsWorker.getPrice(r.getUrl()) <= priceFilter) {
					return r;
				} else
					resultList.remove(random);
			}
		}
		return null;
	}

	public Result getRandomResult() {
		setURL("http://api.yelp.com/v2/search?term=restaurant+food");
		setLl(ll);
		setSort(DEFAULT_SORT);
		setRadius_filter(radius_filter);
		addLocation();
		addSort();
		addRadius();

		String signedURL = YelpURLSigner.getURLString(getURL());
		JsonElement jse = null;
		try {
			jse = JSONWorker.getJSONElementFromString(JSONWorker
					.getJSONString(signedURL));
		} catch (Exception e) {
			e.printStackTrace();
		}

		ArrayList<Result> resultList = new ArrayList<Result>();

		int numResults = Integer
				.parseInt(ResultsWorker.getNumberOfResults(jse));

		if (numResults > 20)
			numResults = 20;

		for (int i = 0; i < numResults; i++) {
			Result r = ResultsWorker.buildResult(ResultsWorker
					.getJsonArrayOfBusinesses(jse).get(i));
			resultList.add(r);
		}

		// the array of Results is fully built here. It can be filtered by
		// preferences here.

		Result r = filterResultList(resultList);
		return r;
	}

	public String getLl() {
		return ll;
	}

	public void setLl(String ll) {
		this.ll = ll;
	}

	public String getCategory_filter() {
		return category_filter;
	}

	public void setCategory_filter(String category_filter) {
		this.category_filter = category_filter;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getRadius_filter() {
		return radius_filter;
	}

	public void setRadius_filter(String radius_filter) {
		this.radius_filter = radius_filter;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public String getOffset() {
		return offset;
	}

	public void setOffset(String offset) {
		this.offset = offset;
	}

	public String getURL() {
		return URL;
	}

	public void setURL(String uRL) {
		URL = uRL;
	}

	public void appendURL(String s) {

		if (!s.equals("")) {
			StringBuilder sb = new StringBuilder();
			sb.append(URL);
			sb.append("&");
			sb.append(s);
			URL = sb.toString();
		}
	}

	public boolean getPricecarec() {
		return pricecare;
	}

	public void setPricecare(boolean pricecare) {
		this.pricecare = pricecare;
	}

	public boolean getNewloc() {
		return newloc;
	}

	public void setNewloc(boolean newloc) {
		this.newloc = newloc;
	}

	public String getLogs() {
		return logs;
	}

	public void setLogs(String logs) {
		this.logs = logs;
	}

	public int getPrice() {
		return pricePreference;
	}

	public void setPrice(int price) {
		this.pricePreference = price;
	}

}
